﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Mysoft.Map6.Core.Common;

namespace MdDocGenerator.Util
{
    public static class AssemblyHelper
    {
        /// <summary>
        /// 获取需要生成文档的方法
        /// </summary>
        /// <param name="dllNames"></param>
        /// <returns></returns>
        public static List<MethodInfo> GetMethods(List<string> dllNames)
        {
            var ignoreMethods = ConfigHelper.IgnoreMethods.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var ignoreServices = ConfigHelper.IgnoreServices.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            List<MethodInfo> list = new List<MethodInfo>();
            foreach (var s in dllNames)
            {
                var assembly = Assembly.LoadFrom(s);
                var typeScope = assembly.GetTypes()
                    .Where(x => x.Namespace != null && ((x.BaseType != null && x.BaseType.Name == "AppService") || x.GetInterface("IPublicService") != null))
                    .Where(x => x.IsSealed == false && x.IsPublic && ignoreServices.Contains(x.Name) == false)
                    .ToList();
                foreach (var type1 in typeScope)
                {
                    var methods = type1.GetMethods()
                        .Where(m => m.GetCustomAttributes(typeof(ForbidHttpAttribute), false).Length < 1)
                        .Where(m => m.IsPublic)
                        .Where(m => m.DeclaringType != null && m.DeclaringType.Namespace == type1.Namespace)
                        .Where(m => ignoreMethods.Contains(m.Name) == false)
                        .ToList();
                    list.AddRange(methods);
                }
            }
            return list;
        }
    }
}